package com.twentyfour.controller;

import com.twentyfour.pojo.Admin;
import com.twentyfour.pojo.Referee;
import com.twentyfour.pojo.Team;
import com.twentyfour.service.AdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@Controller
public class LoginController {
    @Autowired
    @Qualifier("AdminServiceImpl")
    AdminServiceImpl adminService;

    @RequestMapping("/toLogin")
    public String toLogin(Model model){
        return "login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        Model model, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException {


        List<Referee> refereeList = adminService.queryAllReferee();
        List<Admin> adminList = adminService.queryAllAdmin();
        List<Team> teamList = adminService.queryAllTeam();

        //判断管理员登录
        if(request.getParameter("btn").equals("admin")){

            for (Admin admin : adminList) {
                if (admin.getAccount().equals(username)&&admin.getPassword().equals(password)) {
                    session.setAttribute("admin", admin);
                    session.setAttribute("profile", "管理员");
                    response.sendRedirect(request.getContextPath() + "/toMainAdmin");
                }
            }
        }

        //判断代表队登录
        if(request.getParameter("btn").equals("leader")){

            for (Team team : teamList) {
                if(String.valueOf(team.getName()).equals(username)&&team.getPassword().equals(password)) {
                    session.setAttribute("certainTeamId", team.getAccount());
                    session.setAttribute("profile", "领队");
                    return "redirect:toMainLeader";
                }
            }
        }

        //判断裁判登录
        if(request.getParameter("btn").equals("referee")){

            for (Referee referee : refereeList) {
                if(referee.getName().equals(password)&&String.valueOf(referee.getAccount()).equals(username)){
                    session.setAttribute("certainRefereeId",referee.getRefereeId());
                    session.setAttribute("profile","裁判");
                    session.setAttribute("referee",referee);
                    return "redirect:toMainReferee";
                }
            }
        }



        //登录失败，重新返回登录页
        model.addAttribute("msg","请检查输入");
        return "login";
    }
}
